package cn.eonshine.cuba.lsms.modular.basic.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.eonshine.cuba.inf.common.util.DateUtils;
import cn.eonshine.cuba.inf.common.http.InfStatus;
import cn.eonshine.cuba.inf.modular.basic.entity.Customer;
import cn.eonshine.cuba.lsms.modular.CommonService;
import cn.eonshine.cuba.lsms.modular.basic.entity.CustomerLsms;
import cn.eonshine.cuba.lsms.modular.basic.service.ICustomerClientService;
import cn.eonshine.cuba.lsms.modular.basic.service.ICustomerLsmsService;

@Service
public class CustomerClientService extends CommonService<Customer> implements ICustomerClientService{
	
	@Autowired
	private ICustomerLsmsService customerLsmsService;

	private final String listUrl = "/customer/list";
	private final String updateUrl = "/customer/update";
	
	@Override
	public void requestCustomer() {
		requestData(listUrl, updateUrl);
	}
	
	@Override
	protected Object dataHandle(Customer customer) throws Exception {
		QueryWrapper<CustomerLsms> entity = new QueryWrapper<CustomerLsms>();
		entity.eq("CODE", customer.getCode());
		CustomerLsms info = customerLsmsService.getOne(entity);
		boolean isInsert = false;
		if(info == null) {
			info = new CustomerLsms();
			isInsert = true;
		}
		info.setCode(customer.getCode());
		info.setName(StringUtils.trim(customer.getName()));
		info.setFullName(StringUtils.trim(customer.getFullName()));
		info.setRemarks(customer.getRemarks());
		info.setAddress(customer.getAddress());
		info.setStatus(customer.getStatus());

		info.setCreateBy(InfStatus.CREATE_BY);
		info.setUpdateBy(InfStatus.UPDATE_BY);
		Date nowTime = DateUtils.getCubaDate(Calendar.getInstance().getTime());
		if(info.getCreateDate() == null) {
			info.setCreateDate(nowTime);
		}
		info.setUpdateDate(nowTime);
		
		if(isInsert) {
			customerLsmsService.save(info);
		}else {
			customerLsmsService.updateById(info);
		}
		return info;
	}
	@Override
	protected List<Customer> feadBackDataHandle(Object obj, Customer customer, List<Customer> feadBackDataLists) throws Exception {
		CustomerLsms info = (CustomerLsms) obj;
		// 返回进行更新的数据
		Customer tmpBack = new Customer();
		tmpBack.setCode(customer.getCode());
		tmpBack.setName(StringUtils.trim(customer.getName()));
		tmpBack.setDataInputDatetime(customer.getDataInputDatetime());
		tmpBack.setLsmsUpdate(InfStatus.LSMS_UPDATE_EXTRACT_YES);
		tmpBack.setId(info.getId());
		feadBackDataLists.add(tmpBack);
		return feadBackDataLists;
	}
}
